package com.ktjy.service.impl;

import com.ktjy.service.IUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@Service
public class MinioUploadServiceImpl implements IUploadService {

    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secretKey}")
    private String secretKey;
    @Value("${minio.bucketName}")
    private String bucketName;

    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        //根minio服务建立一个连接
        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint(endpoint)
                        .credentials(accessKey, secretKey)
                        .build();
        //判断桶是否存在
        boolean found =
                minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!found) {//如果桶不存在
            //创建桶
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
        //获取文件名全称
        String objectName = file.getOriginalFilename();
        // 获取文件扩展名
        String extension = StringUtils.getFilenameExtension(objectName);
        // 根据UUID拼接文件的扩展名，生成唯一的文件名
        String fileName = UUID.randomUUID() + "." + extension;
        // 以对象(非结构化信息，例如：图片、视频、SQL备份文件、日志文件)的形式存储一个数据信息
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileName)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build());
        System.out.println("上传成功");
        return bucketName + File.separator + fileName;
    }
}
